package test.excel.workbook;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import test.excel.config.ColumnConfig;
import test.excel.dto.CellDto;

public class CellReader {
    private Row row;

    private ColumnConfig config;

    private SheetHeader header;

    public CellReader(Row row, ColumnConfig config, SheetHeader header) {
        this.row = row;
        this.config = config;
        this.header = header;
    }

    public CellDto read() {
        int colIndex = getColIndex(config, header);

        try {
            Cell cell = row.getCell(colIndex, Row.RETURN_BLANK_AS_NULL);

            if (cell == null) return new CellDto(null, null);

            switch (config.getType()) {
                case CellDto.COL_INT    : return new CellDto(config.getType(), (int) cell.getNumericCellValue());
                case CellDto.COL_DOUBLE : return new CellDto(config.getType(), cell.getNumericCellValue());
                case CellDto.COL_DATE   : return new CellDto(config.getType(), cell.getDateCellValue());
                case CellDto.COL_STRING : return new CellDto(config.getType(), cell.getStringCellValue());
                default: throw new IllegalStateException();
            }
        } catch (Exception e) {
            throw new IllegalStateException("Read from row " + row.getRowNum() + " and column " + colIndex, e);
        }
    }

    private int getColIndex(ColumnConfig columnConfig, SheetHeader header) {
        Integer colIndex = columnConfig.getIndex();

        if (colIndex == null) {
            colIndex = header.getIndexByName(columnConfig.getSheetColName());

            if (colIndex == null) throw new IllegalStateException("Column with name " + columnConfig.getSheetColName().trim() + " not found.");
        }

        return colIndex;
    }
}
